<template>
  <div class="view-main" v-loading="loading">
    <div class="view-main-header">
      <h2 class="view-main-title">课程</h2>
      <el-button class="main-title-back" type="primary" @click="addLesson()">{{lessonStatus}}课程</el-button>
      <el-button type="warning" @click="importLesson()">导入课程</el-button>
      <el-input clearable placeholder="请输入要搜索的课程名称" v-model="lessonSearchName" class="input-with-select">
        <template #append>
          <el-button class="input-with-button" @click="searchLesson">搜索</el-button>
        </template>
      </el-input>
      <router-link class="main-title-back" :to="{path: '/major', query: {
          id:route.query.id,  // 学校ID
          departments_id:route.query.departments_id,  //学院ID
          areas_id:route.query.areas_id,
          logo:route.query.logo,
          name:route.query.name,
          name_zh:route.query.name_zh,
          qs:route.query.qs,}}">
          <el-button>返回上一级</el-button>
      </router-link>
    </div>
    <div class="view-main-table">
      <el-table :max-height='state.posheight' v-if="state.listData.length > 0" :data="state.listData" border>
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="课程名称" show-overflow-tooltip align="center">
          <template #default="scope">{{ scope.row.name_zh }}</template>
        </el-table-column>
        <el-table-column label="课程英文名称" show-overflow-tooltip align="center">
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
      </el-table>
      <div v-else class="right-view-nodata">
        <img src="@/assets/img/no-data.png" alt="">
        <div>暂无数据</div>
      </div>
    </div>
  </div>
  <el-dialog
    width="60%"
    title="新增/编辑课程"
    :close-on-click-modal="false"
    v-model="lessonVisible">
    <addLessonView v-if="lessonVisible" @closeAddLesson='closeAddLesson' :parmas="{list:state.listData,degrees_id:route.query.degrees_id}"></addLessonView>
  </el-dialog>
  <el-dialog
    width="20%"
    title="请选择Excel文件导入课程"
    :close-on-click-modal="false"
    v-model="batchLessonVisible">
    <div v-if="batchLessonVisible" style="margin-top: 15px;">
      <div class="view-main-table-upload">
        <input type="file" @change="handleFileChange" accept=".xlsx, .xls">
      </div>
      <el-form ref="form" label-width="130px">
        <el-form-item label="是否保留原课程：">
          <el-radio-group v-model="keep_old">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="uploadFile">提交</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
  import { useRoute ,useRouter} from "vue-router";
  import addLessonView from '../schoolComponents/add-lesson.vue'
  const route = useRoute()
  // const router = useRouter()
  import { ref,reactive,onMounted,watch } from 'vue';
  import { ElMessage , } from 'element-plus';
  import API from "@/utils/api";
  import { serverUrl } from '@/utils/const'
  import axios from 'axios';
  import router from "@/router/index";
  const queryInfo = ref(route.query)
  // console.log(queryInfo,'queryInfo');
  let keep_old = ref(1)
  let loading = ref(false)
  let lessonVisible = ref(false)
  let lessonSearchName = ref('')
  let operationStatus = ref(localStorage.getItem('operationStatus'))
  let lessonStatus = ref('新增')
  let batchLessonVisible = ref(false)
  let selectedFile = ref(null)
  const importLesson = (() => {
    batchLessonVisible.value = true
  })
  const handleFileChange = (event) => {
    selectedFile.value = event.target.files[0];
  };
  async function uploadFile() {
    if(!selectedFile.value) {
      return ElMessage.warning('请选择要上传的excel文件')
    }
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    formData.append("degrees_id",queryInfo.value.degrees_id);
    formData.append("keep_old",keep_old.value);
    try {
      const response = await axios.post(serverUrl+'/admin/course/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token-admin': localStorage.getItem('token'),
        }
      });
      if(response.data.code === 0) {
        batchLessonVisible.value = false
        getLessonList()
        ElMessage.success('导入成功')
      }
      if(response.data.code === 401) {
        ElMessage.warning('未登录')
        router.push({path: '/'})
        localStorage.removeItem('token')
        localStorage.removeItem('operationStatus')
      }
    } catch (error) {}
  }
  const state = reactive({
    listData:[],
    h: document.body.clientHeight,
    posheight: 100,
    timer: false,
  })
  watch(() => state.h, (newValue, oldValue) => {
    if(!state.timer) {
      state.posheight = newValue - 130
      state.timer = true
      setTimeout(function (){
        state.timer = false
      },400)
    }
  })
  function posTableHeight () {
    let h = document.body.clientHeight,
    new_h = h - 130;
    state.posheight = new_h;
  }
  const addLesson = (() => {
    lessonVisible.value = true
  })
  const closeAddLesson = ((type) => {
    lessonVisible.value = false
    if(type === 2) {
      getLessonList()
    }
    getListData()
  })
  const getListData = (() => {
    state.listData.forEach((item,index) => {
      if(!item.name && !item.name_zh) {
        delete state.listData[index]
      }
    })
    const listData_ = state.listData.filter(item => item !== "" && item !== null && item !== undefined);
    state.listData = listData_
  })
  const searchLesson = (() => {
    getLessonList()
  })
  // 获取课程数据
  const getLessonList = (() => {
    loading.value = true
    API.lessonList.getLessonList({degrees_id:queryInfo.value.degrees_id,name:lessonSearchName.value},(res) =>{
      loading.value = false
      if(res.code == 0) {
        state.listData = res.data
        if (res.data.length > 0) {
          lessonStatus.value = '编辑'
        }
      }
    })
  })
  onMounted(() => {
    getLessonList()
    posTableHeight()
    window.onresize = () => {
      return (() => {
        let a = document.body.clientHeight
        state.h = a
      })()
    }
  })
</script>

<style lang="scss" scoped>
.view-main {
  padding: 0 20px 20px;
  position: relative;
  .view-main-header {
    display: flex;
    align-items: center;
    .main-title-back {
      margin-left: 20px;
    }
    .el-input-group {
      width: 30%;
      margin-left: 20px;
    }
    .input-with-button {
      color: #fff;
      background: #409eff;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
  .view-main-table {
    .right-view-nodata {
      margin-top: 160px;
    }
  }
}
.view-main-table-upload {
  margin-bottom: 20px;
  text-align: start;
}
</style>